﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace NGinnBPM.Lib.Operations
{
    [DataContract]
    [KnownType(typeof(int[]))]
    [KnownType(typeof(string[]))]
    [KnownType(typeof(DateTime?[]))]
    [KnownType(typeof(DateTime[]))]
    [KnownType(typeof(double[]))]
    [KnownType(typeof(DataField[]))]
    [KnownType(typeof(bool[]))]
    public class DataField
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public object Val { get; set; }
    }

    public class DataFieldHelper
    {
        static List<DataField> FromDictionary(IDictionary<string, object> d)
        {
            List<DataField> l = new List<DataField>();
            foreach (string k in d.Keys)
            {
                object v = d[k];
                DataField df = new DataField { Name = k };
                if (v == null)
                {
                }
                else if (v.GetType().IsValueType)
                {
                    df.Val = v;
                }
                else if (v.GetType().IsArray)
                {
                    var et = v.GetType().GetElementType();
                    if (et.IsValueType)
                    {
                        df.Val = v;
                    }
                    else if (et == typeof(IDictionary<string, object>))
                    {
                        df.Val = FromDictionary((IDictionary<string, object>)(v));
                    }
                    else throw new Exception("Unexpected data type:" + v);
                }
                
                l.Add(df);
            }
            return l;
        }

        static object ToDataFieldValue(object v)
        {
            if (v == null) return v;
            if (v.GetType().IsValueType) return v;
            if (v is IDictionary<string, object>) return FromDictionary((IDictionary<string, object>)(v));
            if (v is IEnumerable<int> || v is IEnumerable<string> || v is IEnumerable<bool>
                || v is IEnumerable<DateTime> || v is IEnumerable<double>)
            {
            }
            if (v.GetType().IsArray)
            {
                var et = v.GetType().GetElementType();
                if (et.IsValueType)
                {
                    return v;
                }
                else if (typeof(IDictionary<string, object>).IsAssignableFrom(et))
                {
                    var ret = new List<DataField>();
                    return ret;
                }
                else throw new Exception("Unexpected data type:" + v);
            }
            throw new Exception("Unexpected type:" + v);
            
        }

        static Dictionary<string, object> ToDictionary(List<DataField> l)
        {
            throw new NotImplementedException();
        }
    }
}
